package com.woniu.park.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.park.controller.form.UserForm;
import com.woniu.park.dao.*;
import com.woniu.park.entity.*;
import com.woniu.park.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.park.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxb
 * @since 2020-09-05
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ParkspaceMapper parkspaceMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private TotalorderMapper totalorderMapper;
    @Override
    public User findByUsername(String principal) {
        return null;
    }

    @Override
    public Set<String> findRoleById(Integer userId) {
        return null;
    }

    @Override
    public Set<String> findPermById(Integer userId) {
        return null;
    }

    @Override
    public int acquireId(String userIdnumber) {

        return userMapper.acquireId(userIdnumber);
    }

    /*
          注册
       */
    public Result registerCode(UserForm userForm) {
        User user = new User();
        //将userForm复制给user
        BeanUtils.copyProperties(userForm, user);
        //校验邀请码是否存在，若存在获取该推送用户id
        //校验邀请码是否存在，若存在获取该推送用户id
        //System.out.println(user.getUserRegistIsnumber());
        //System.out.println(user.getUserName());
        //无邀请码注册
        if (userForm.getUserRegistIsnumber() == null || userForm.getUserRegistIsnumber() == "") {
            if (userForm.getUserType() == 1) {
                //租客注册
                user.setUserRegistNumber(RandomId.getRandomId());
                //生成随机盐
                String salt = RandomId.getRandomId();
                String userPassword = user.getUserPassword();
                user.setUserSault(salt);
                user.setUserLicense(user.getUserLicense());
                //密文加密
                user.setUserPassword(EncryptUtil.encrypt(userPassword, salt));
                user.setUserType(Status.USER_STATUS1);
                //执行新增
                userMapper.insert(user);
                //分配权限
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(Status.USER_STATUS1);
                userRoleMapper.insert(userRole);
                return Result.success("1", "租客无邀请劵注册");
            } else if (userForm.getUserType() == 2) {
                //出租方
                user.setUserRegistNumber(RandomId.getRandomId());
                //生成随机盐
                String salt = RandomId.getRandomId();
                String userPassword = user.getUserPassword();
                user.setUserSault(salt);
                //密文加密
                user.setUserPassword(EncryptUtil.encrypt(userPassword, salt));
                user.setUserType(Status.USER_STATUS2);
                user.setUserLicense(user.getUserLicense());
                //执行新增
                userMapper.insert(user);
                //分配权限
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(Status.USER_STATUS2);
                userRoleMapper.insert(userRole);
                return Result.success("1", "出租方无邀请码注册");
            } else {
                return Result.fail("30000", "请选择注册类型注册");
            }
        } else {
            User user2 = userMapper.selectInviter(user.getUserRegistIsnumber());
            int inviter = user2.getUserId();
            //邀请码
            if (userForm.getUserType() == 1) {
                //租客注册
                if (user2 != null) {
                    System.out.println(inviter);

                    //注册新增
                    //生成生成邀请码
                    user.setUserRegistNumber(RandomId.getRandomId());
                    //生成随机盐
                    String salt = RandomId.getRandomId();
                    String userPassword = user.getUserPassword();
                    user.setUserSault(salt);
                    //密文加密
                    user.setUserPassword(EncryptUtil.encrypt(userPassword, salt));
                    user.setUserType(Status.USER_STATUS1);
                    user.setUserLicense(user.getUserLicense());
                    //执行新增
                    userMapper.insert(user);
                    //分配权限
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(1);
                    userRoleMapper.insert(userRole);
                    //给邀请码注册添加代金券
                    Coupon coupon = new Coupon();
                    //一次默认生成一张代金券
                    coupon.setCouponNumber(1);
                    //类型写死1
                    coupon.setCouponType(1);
                    coupon.setCouponDiscount(20);
                    coupon.setCouponCondition(50);
                    coupon.setUserId(user.getUserId());
                    couponMapper.insert(coupon);
                    //判断推荐注册码的用户是否是租户,是则添加代金卷
                    if (user2.getUserType() == Status.ORDER_STATUS1) {
                        Coupon couponInviter = new Coupon();
                        //一次默认生成一张代金券
                        couponInviter.setCouponNumber(1);
                        //类型写死1
                        couponInviter.setCouponType(1);
                        couponInviter.setCouponDiscount(20);
                        couponInviter.setCouponCondition(50);
                        couponInviter.setUserId(inviter);
                        couponMapper.insert(couponInviter);
                        //该推荐码只能推荐一人，所以当被推荐人组成成功且发邀人代金卷获取成功，删除该邀请人的邀请码
                        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
                        wrapper.set("user_regist_number", "已使用").eq("user_id", inviter);
                        userMapper.update(null, wrapper);
                    }
                    return Result.success("1", "租客用邀请码注册");
                } else {
                    return Result.fail("20007", "邀请码错误");
                }
            } else {
                //出租方
                user.setUserRegistNumber(RandomId.getRandomId());
                //生成随机盐
                String salt = RandomId.getRandomId();
                String userPassword = user.getUserPassword();
                user.setUserSault(salt);
                //密文加密
                user.setUserPassword(EncryptUtil.encrypt(userPassword, salt));
                user.setUserType(Status.USER_STATUS2);
                user.setUserLicense(user.getUserLicense());
                //执行新增
                userMapper.insert(user);
                //分配权限
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(Status.USER_STATUS2);
                userRoleMapper.insert(userRole);
                //判断推荐注册码的用户是否是租户,是则添加代金卷
                if (user2.getUserType() == Status.ORDER_STATUS1) {
                    Coupon couponInviter = new Coupon();
                    //一次默认生成一张代金券
                    couponInviter.setCouponNumber(1);
                    //类型写死1
                    couponInviter.setCouponType(1);
                    couponInviter.setCouponDiscount(20);
                    couponInviter.setCouponCondition(50);
                    couponInviter.setUserId(inviter);
                    couponMapper.insert(couponInviter);
                    //该推荐码只能推荐一人，所以当被推荐人组成成功且发邀人代金卷获取成功，删除该邀请人的邀请码
                    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
                    wrapper.set("user_regist_number", "已使用").eq("user_id", inviter);
                    userMapper.update(null, wrapper);
                }
                return Result.success("1", "出租方用邀请码注册");
            }
        }

    }
    /*
        已经注册用户生成推荐码

     */
   /* public String code(int userId) {
        String CODE = UUID.randomUUID().toString().substring(0,6);
        return CODE;
    }
*/
    public String code(int userId) {
        User user = userMapper.selectById(userId);
        String CODE = user.getUserRegistNumber();
        return CODE;
    }
    @Override
    public List<Order> findByParkspaceIdNotStatus(List<Integer> parkspaceIds) {
        List<Order> order = orderMapper.selectList(new QueryWrapper<Order>().in("order_parkspace_id", parkspaceIds));
        return order;
    }

    @Override
    /*
        修改密码
     */
    public void changePassword(int userId,String confirmPassword) {
        //生成随机盐,并更新到数据库中
        String salt = RandomId.getRandomId();
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("user_password",EncryptUtil.encrypt(confirmPassword,salt)).set("user_sault",salt).eq("user_id",userId);

        log.info("用户ID：{}，密码为：{}",userId,EncryptUtil.encrypt(confirmPassword,salt));
        userMapper.update(null,wrapper);
    }
    /*
        短信验证登录
     */
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        //  连接阿里云  第二个参数是密钥id 第三个参数是密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GGwZ2293tuSLAZWZVYb", "twnQYr4F5yFF83m6IN9AOaDTUuPfEy");
        IAcsClient client = new DefaultAcsClient(profile);
        //构件请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//定死不修改
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //自定义的参数（手机号，签名，模板,验证码！）
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "蜗牛共享车位");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }


    @Override
    public List<Parkspace> findParkById(int userId) {
        QueryWrapper wrapper = new QueryWrapper<Parkspace>();
        wrapper.eq("user_id",userId);
        List<Parkspace> list = parkspaceMapper.selectList(wrapper);
        return list;
    }

    @Override
    public Order findByParkspaceId(int parkspaceId) {
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_parkspace_id", parkspaceId).eq("order_status",0));

        return order;
    }

    @Override
    public User findByUserId(int orderUserId) {

        return userMapper.selectById(orderUserId);
    }
}
